#!/usr/bin/python
# -*-coding:utf-8-*-
# pip install ddddocr 图片识别
"""江苏省危险废物监控系统"""
import asyncio
import os
from datetime import datetime
from time import sleep

import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from pyppeteer import launch

import common
import db

mysqldb = db.DbManager()

load_dotenv(verbose=True)
# 今天
today_time = common.TodayTime()
# 将-替换为.
today_time_new = today_time.replace('-', '.')
# 账号
username = os.getenv('LOGIN_ADMIN')
passworld = os.getenv('LOGIN_PWD')
url = os.getenv('URL')
username_1 = os.getenv('LOGIN_ADMIN_1')
passworld_1 = os.getenv('LOGIN_PWD_1')
url_1 = os.getenv('URL_1')

# 存储登录后cookie
new_cookies = ""

async def login_2():
    now_day = datetime.now().strftime('%Y-%m-%d')
    # userDataDir:记录上网记录 是否已登录等。。 userDataDir='./userdata',
    browser = await launch(headless=True, userDataDir='./userdata', args=['--disable-infobars', '--no-sandbox'])
    page = await browser.newPage()
    await page.setUserAgent(
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER")
    await page.setViewport(viewport={'width': 1536, 'height': 768})

    await page.setJavaScriptEnabled(enabled=False)
    await page.evaluateOnNewDocument('() =>{ Object.defineProperties(navigator,'
                                     '{ webdriver:{ get: () => false } }) }')

    await page.goto(url)
    # 查看title 是否等于
    login_text = await page.querySelectorAllEval('#toLogin', 'nodes=>nodes.map(node=>node.innerText)')
    print(str(login_text))
    print("到这边")
    if "登" in str(login_text[0]):
        print("点击登录")
        # 点击登录
        await page.type(
            '#uname',
            username)
        await page.type(
            '#upassword',
            passworld, {'delay': 120})
        # 识别图片二维码
        print("开始识别图片验证码")
        # 标签截图 不删
        img = await page.querySelector('#image')
        await img.screenshot(path='CODE_IMG.png')
        import ddddocr
        ocr = ddddocr.DdddOcr(old=True)

        with open("CODE_IMG.png", 'rb') as f:
            image = f.read()
        # 识别后的验证码
        res = ocr.classification(image)
        # 替换 res
        if "u" in res:
            res = res.replace('u', '5')
        if "o" in res:
            res = res.replace('o', '0')
        if "l" in res:
            res = res.replace('l', '1')
        if "i" in res:
            res = res.replace('i', '1')
        print('识别出的验证码为：' + res)
        sleep(0.5)
        await page.type('#input1', res, {'delay': 100})
        sleep(1)
        # 点击登录
        await page.click("#toLogin")
        sleep(0.5)
        sleep(1)
    # 双击
    sleep(5)
    # # 获取并保存cookies
    page_cookie = await page.cookies()
    cookies = ''
    for cookie in page_cookie:
        str_cookie = '{0}={1};'
        str_cookie = str_cookie.format(cookie.get('name'), cookie.get('value'))
        cookies += str_cookie
    print(cookies)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X -1_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
        'Accept': '*/*',
        'Host': '218.92.31.102:8400',
        'Origin': 'http://180.101.234.11:20002',
        'Referer': 'http://180.101.234.11:20002/main/view/exceptionRecord/list.html?ticketId=BD2F4405-3F23-4600-AACA-17C07F82FE37&type=overOneYearInventory&message=%E8%B6%85%E4%B8%80%E5%B9%B4%E6%9C%9F%E5%BA%93%E5%AD%98%E5%BC%82%E5%B8%B8&canBack=1',
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cookie': cookies
    }
    # 核与辐射作业
    payload = 'areaCode=&entName=&beginTime=2022-01-01&endTime='+now_day+'&transferNo=&status=&current=1&size=10&totalRecord=0&ticketId=BD2F4405-3F23-4600-AACA-17C07F82FE37&type=overOneYearInventory&isEpa=true'
    resp = requests.post(
        "http://180.101.234.11:20002/solidwaste/exceptionRecord/list",
        headers=headers, data=payload)
    print(resp)
    print(resp.text)
    result = resp.json()  # 转化
    try:
        if int(result['total'])>0:
            for i in range(len(result['obj']['list'])):
                # recordTime description
                desc = result['obj']['list'][i]['recordTime'] + "_" + result['obj']['list'][i]['description'] + "_" + \
                       result['obj']['list'][i]['id']
                # 检查是否存在数据 如果存在数据则跳过
                find_count = mysqldb.table_select_one(table="xw_event_alarm", where={"note": desc
                                                                                     })
                if find_count:
                    continue
                info = {"type": 7,
                        "name": "危废超期贮存",
                        "push_type": 7,
                        "push_name": "超一年期库存异常",
                        "push_time": result['obj']['list'][i]['recordTime'],
                        "note": desc,
                        'create_time': now_day,
                        }
                mysqldb.table_insert(table="xw_event_alarm", data=info)
    except:
        exit()


class Egas:
    def __init__(self):
        self.url = url
        self.main()

    def main(self):
        asyncio.get_event_loop().run_until_complete(login_2())

Egas()
